package com.programmingfree.springservice.controller;


import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import sun.security.action.GetLongAction;
import utility.Codigos;

import com.programmingfree.springservice.domain.Funcionario;
import com.programmingfree.springservice.domain.Notificacion;
import com.programmingfree.springservice.domain.Oficina;
import com.programmingfree.springservice.domain.User;

//@Controller
@RestController
@RequestMapping("/service/greeting")

public class SpringServiceController {
	
	
	private String message;
	
	
	@RequestMapping(value = "getFuncsByOffice/{officeId}", method = RequestMethod.GET, headers="Accept=application/json")
	public List<Funcionario> getFuncsByOffice(@PathVariable int officeId) {
		//Buscar el user con el id=userId y retornarlo
		ArrayList<Funcionario> resp = new ArrayList<Funcionario>();
		for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
			if(func.getOficina().getId()==officeId){
				resp.add(func);
			}
		}
		return resp;
	}
	
	
	@RequestMapping(value = "getOffice/{officeId}", method = RequestMethod.GET, headers="Accept=application/json")
	public Oficina getOffice(@PathVariable int officeId) {
		//Buscar el user con el id=userId y retornarlo
		for (Oficina oficina : FacadeServices.getInstance().getListOficinas()) {
			if(oficina.getId()==officeId){
				return oficina;
			}
		}
		return null;
	}
	
	@RequestMapping(value = "user/{id}", method = RequestMethod.GET,headers="Accept=application/json")
	public User getUser(@PathVariable String id) {
		
		int user_id=Integer.parseInt(id);
		for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
			if(func.getUserid()==user_id){
				return func;
			}
		}
		return null;
		
		/*String result="Hello "+name;		
		return result;*/
	}
	
	
	
	
	@RequestMapping(value = "allUsers/{tipo}", method = RequestMethod.GET,headers="Accept=application/json")
	public ArrayList<Funcionario> getUsers(@PathVariable String tipo) {
		if(tipo.equals(Codigos.CODIGO_PASILLO)){
			return FacadeServices.getInstance().getListTotalFuncionarios();
		}
		return null;
	}
	
	@RequestMapping(value = "allOfficines", method = RequestMethod.GET,headers="Accept=application/json")
	public ArrayList<Oficina> getOficinas() {
		
		return FacadeServices.getInstance().getListOficinas();
	}

	@RequestMapping(value="/image/{id}", method={RequestMethod.GET}, produces="image/png")
	@ResponseBody public byte[] getImage(HttpServletResponse resp,@PathVariable String id) throws IOException {
		try {
	        // Retrieve image from the classpath.
			
			String  path = "/"+id+".jpg";
			InputStream is = this.getClass().getResourceAsStream(path); 

	        // Prepare buffered image.
	        BufferedImage img = ImageIO.read(is);

	        // Create a byte array output stream.
	        ByteArrayOutputStream bao = new ByteArrayOutputStream();

	        // Write to output stream
	        ImageIO.write(img, "jpg", bao);

	        return bao.toByteArray();
	    } catch (IOException e) {
	    	//throw new RuntimeException(e);
	    	return null;
	    }
	
	}
	
	
	@RequestMapping(value = "/state", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody User setAviability(@RequestParam boolean estado,@RequestParam int userId,@RequestParam String message) {
		//Buscar el user con el id=userId y retornarlo
		
		User user = new User();
		for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
			if(func.getUserid()==userId){
				func.setDisponible(estado);
				func.setMensajeNoDisponible(message);
				user.setFirstName(func.getFirstName());
				user.setLastName(func.getLastName());
				user.setDisponible(func.isDisponible());
				user.setMensajeNoDisponible(message);
			}
		}
		return user; 
	}
	
	@RequestMapping(value = "/setNotification", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody Boolean setNotification(@RequestParam int funcID,@RequestParam int userId,@RequestParam int officeId,@RequestParam String userName,@RequestParam String message) {
		//Buscar el user con el id=userId y retornarlo
		
		for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
			if(func.getUserid()==funcID){
				Notificacion n = new Notificacion();
				n.setUserId(userId);
				n.setMessage(message);
				n.setUserName(userName);
				n.setOfficeId(officeId);
				SimpleDateFormat formatter = new SimpleDateFormat(
						"dd/MM/yyyy HH:mm");
				String s = formatter.format(new Date());
				Date d;
				try {
					d = (Date) formatter.parseObject(s);
					n.setFecha(d);
				} catch (ParseException e) {
					System.out.println(e.getMessage());
				}
				func.getNotificaiones().add(n);
				return   true;
			}
		}
		return false;
	}

	
	
	@RequestMapping(value = "/getNotification", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody List<Notificacion> getNotification(@RequestParam int funcID,@RequestParam int officeId) {
		//Buscar el user con el id=userId y retornarlo
		ArrayList<Notificacion> resp = new ArrayList<Notificacion>();
		for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
			if(func.getUserid()==funcID){
				for (Notificacion noti : func.getNotificaiones()) {
					if(noti.getOfficeId() == officeId){
						resp.add(noti);
					}
				}
				return resp;
			}
		}
		return null;
	}
	
	@RequestMapping(value = "/isLoguedUser", method = RequestMethod.POST,produces="application/json")
	public @ResponseBody User isLoguedUser(@RequestParam String user,@RequestParam String pass) {
		String tipoUsuario = FacadeServices.getInstance().identificarTipoUsuario(user);
		if(tipoUsuario.equals(Codigos.USUARIO_FUNCIONARIO)){
			for (Funcionario func : FacadeServices.getInstance().getListTotalFuncionarios()) {
				if(func.getEmail().equals(user)){
					if(func.getPassword().equals(pass)){
						return func;
					}
				}
			}
			
			
		}else{
			for (User est : FacadeServices.getInstance().getListTotalEstudiantes()) {
				if(est.getEmail().equals(user)){
					if(est.getPassword().equals(pass)){
						return est;
					}
				}
			}
			//TODO: recorrer listado de Estudiantes
		}
		return null;
		
		/*String result="Hello "+name;		
		return result;*/
	}

	
	private String getImagePath(Long id){
		if(id ==1){
			return "/1.jpg";
		}else
		{
			if(id ==2){
				return "/2.jpg";
			}
		}
		return "";
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}